package com.funny.stock.util;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Base64Utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class ShaPasswordEncoder implements PasswordEncoder {

    public ShaPasswordEncoder() {

    }

    @Override
    public String encode(CharSequence rawPassword) {
        return getEncodedPassword(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return encodedPassword.equals(getEncodedPassword(rawPassword));
    }

    private String getEncodedPassword(CharSequence rawPassword){
        String encodedPassword = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            byte[] data = digest.digest(rawPassword.toString().getBytes());
            encodedPassword = Base64Utils.encodeToString(data);
            System.out.println(encodedPassword);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return encodedPassword;
    }
}